<template>
    <div class="app-container">
        <div class="filter-container">
            <el-input placeholder="请输入名称" v-model="listQuery.name" style="width: 150px;" class="filter-item" @keyup.enter.native="handleFilter" />
            <el-select v-model="listQuery.type" placeholder="请选择类型" clearable style="width: 150px" class="filter-item">
                <el-option v-for="item in types" :key="item" :label="item" :value="item" />
            </el-select>
            <el-select v-model="listQuery.fr" placeholder="请选择来源" clearable class="filter-item" style="width: 150px">
                <el-option v-for="item in frs" :key="item" :value="item" />
            </el-select>
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-eye" @click="handlePreview">预览</el-button>
        </div>
        <el-table v-loading="listLoading" :key="tableKey" :data="list" border fit highlight-current-row style="width: 100%;" @sort-change="sortChange">
            <el-table-column label="名称" prop="id" sortable align="left" min-width="200px">
                <template slot-scope="scope">
                    <span>{{ scope.row.name }}</span>
                </template>
            </el-table-column>
            <el-table-column label="类型" width="100px" align="left">
                <template slot-scope="scope">
                    <span>{{ scope.row.type }}</span>
                </template>
            </el-table-column>
            <el-table-column label="来源" width="100px" align="left">
                <template slot-scope="scope">
                    <span>{{ scope.row.fr}}</span>
                </template>
            </el-table-column>
            <el-table-column label="图片" width="110px" align="left">
                <template slot-scope="scope">
                    <div style="width: 50px;height:50px;" v-viewer="{movable: false, toolbar: false, url: 'data-source'}">
                        <img v-lazy="scope.row.thumbnail" :key="scope.row.thumbnail" :data-source="scope.row.url" style="max-width: 50px;max-height: 50px;">
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="状态" class-name="status-col" width="100">
                <template slot-scope="scope">
                    <el-tag type="success">{{ scope.row.status | statusFilter }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="left" width="230" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
                    <el-button v-if="scope.row.status!=2" size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.pageSize" @pagination="getList"/>
        <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
            <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:30px;margin-right:30px;">
                <el-form-item label="名称" prop="title">
                    <el-input v-model="temp.name" placeholder="请输入名称" style="width:100%;"/>
                </el-form-item>
                <el-form-item label="类型" prop="title">
                    <el-select v-model="temp.type" class="filter-item" placeholder="请选择类型" style="width:100%;">
                        <el-option v-for="item in types" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="来源" prop="title">
                    <el-select v-model="temp.fr" class="filter-item" placeholder="请选择来源" style="width:100%;">
                        <el-option v-for="item in frs" :key="item" :label="item" :value="item" />
                    </el-select>
                </el-form-item>
                <el-form-item label="图片地址" prop="title">
                    <el-input v-model="temp.url" placeholder="请输入图片地址" style="width:100%;"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
            </div>
        </el-dialog>
        <div class="images" v-viewer="{movable: false, toolbar: true}">
            <img v-for="item in images" :src="item" :key="item" style="max-width: 50px;max-height: 50px;">
        </div>
    </div>
</template>
<script>
import { fetchList, addPhoto, updatePhoto, deletePhoto } from '@/api/crawler/photo';
import waves from '@/directive/waves';
import Pagination from '@/components/Pagination';
import 'viewerjs/dist/viewer.css'
import Viewer from 'v-viewer'
import Vue from 'vue'
Vue.use(Viewer)

export default {
    name: 'photo',
    filters: {
        statusFilter(status) {
            const statusMap = {
                '1': '正常',
                '2': '已删除'
            }
            return statusMap[status]
        }
    },
    directives: { waves },
    components: { Pagination },
    data() {
        return {
            tableKey: 0,
            list: null,
            images: [],
            listLoading: true,
            listQuery: {
                name: '',
                type: '',
                fr: '',
                status: '',
                page: 1,
                pageSize: 10
            },
            types: ['美女养眼', '生活风景', '高清壁纸', '创意设计'],
            frs: ['08绿软站', 'wallhaven'],
            total: 0,
            temp: {
                id: undefined,
                name: '',
                type: '',
                fr: '',
                url: ''
            },
             rules: {
                name: [{ required: true, message: '名称必填', trigger: 'blur' }],
                type: [{ required: true, message: '类型必选', trigger: 'change' }],
                fr: [{ required: true, message: '来源必选', trigger: 'change' }],
                url: [{ required: true, message: '图片地址必填', trigger: 'blur' }]
            },
            textMap: {
                update: '编辑',
                create: '新增'
            },
            dialogStatus: '',
            dialogFormVisible: false
        }
    },
    created() {
        this.getList();
    },
    methods: {
        handlePreview() {
            const viewer = this.$el.querySelector('.images').$viewer
            viewer.show()
        },
        getList() {
            this.listLoading = true;
            fetchList(this.listQuery).then(res => {
                this.list = res.data.data.list;
                this.total = res.data.data.total;
                this.listLoading = false;
                let images = [];
                for (let item of this.list) {
                    images.push(item.url);
                }
                this.images = images;
            }).catch(err => {
                throw new Error('错误：' + err);
            })
        },
        handleFilter() {
            this.listQuery.page = 1
            this.getList()
        },
        handleCreate() {
            this.dialogStatus = 'create';
            this.dialogFormVisible = true;
            this.temp = {
                id: undefined,
                name: '',
                type: '',
                fr: '',
                url: ''
            };
        },
        sortChange(data) {
            console.log(data)
        },
        handleDelete(row) {
            this.$confirm('确定要删除吗?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                center: true
            }).then(() => {
                deletePhoto({
                    ids: [row.id]
                }).then(() => {
                    this.dialogFormVisible = false
                    this.$notify({
                        title: '成功',
                        message: '删除成功!',
                        type: 'success',
                        duration: 2000
                    });
                    this.listQuery.page = 1;
                    this.getList();
                });
            });
        },
        handleUpdate(row) {
            this.temp = Object.assign({}, row);
            this.dialogStatus = 'update';
            this.dialogFormVisible = true;
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate();
            })
        },
        createData() {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    addPhoto(this.temp).then(() => {
                        this.dialogFormVisible = false
                        this.$notify({
                            title: '成功',
                            message: '创建成功',
                            type: 'success',
                            duration: 2000
                        });
                        this.listQuery.page = 1;
                        this.getList();
                    })
                }
            })
        },
        updateData() {
            this.$refs['dataForm'].validate((valid) => {
                if (valid) {
                    const tempData = Object.assign({}, this.temp)
                    updatePhoto(tempData).then(() => {
                        this.dialogFormVisible = false
                        this.$notify({
                            title: '成功',
                            message: '更新成功',
                            type: 'success',
                            duration: 2000
                        })
                        this.getList();
                    })
                }
            })
        }
    }
}

</script>

<style lang="scss" scoped>
    .filter-container {
        padding-bottom: 10px;
    }
    .images {
        display: none;
    }
</style>
